/*
 * CLASS: MainPage.java
 */

package view;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import model.*;

/**
 *
 * @author Samuele Mattiuzzo
 */
public class MainPage extends javax.swing.JFrame {

    private Library library;
    private User user;
    private LoginWindow login;
    MainPage(Library lib, User us, LoginWindow l) {
        library = lib;
        user = us;
        login = l;
        initComponents();
        jLabelCurrent.setText("Benvenuto, "+user.getUsername());
        if(!user.canRent()){
            // login se utente e' bloccato
            jLabel2.setText("Impossibile effettuare prenotazioni.\nRestituire i prestiti scaduti.");
            jDialog1.setVisible(true);
            jButtonSearch.setVisible(false);
            jButtonAdminLoans.setVisible(false);
        }
        if(!user.isSuperuser()){
            // login da utente normale
            jButtonAdminAuthors.setVisible(false);
            jButtonAdminUsers.setVisible(false);
            jButtonAdminProducts.setVisible(false);
            jButtonAdminBlock.setVisible(false);
            jButtonAdminConfirm.setVisible(false);
            tableLoad();
        }else{
            // login da super utente
            int viewColumn = jTable1.convertColumnIndexToView(5);
            TableColumn column = jTable1.getColumnModel().getColumn(viewColumn);
            column.setHeaderValue("BLOCCATO");
            jTable1.getTableHeader().repaint();
            jButtonReturn.setVisible(false);
            tableLoadAdmin();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDialog1 = new javax.swing.JDialog();
        jLabel2 = new javax.swing.JLabel();
        jButtonSearch = new javax.swing.JButton();
        jLabelCurrent = new javax.swing.JLabel();
        jButtonLogout = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButtonReturn = new javax.swing.JButton();
        jButtonAdminAuthors = new javax.swing.JButton();
        jButtonAdminUsers = new javax.swing.JButton();
        jButtonAdminLoans = new javax.swing.JButton();
        jButtonAdminProducts = new javax.swing.JButton();
        jButtonAdminConfirm = new javax.swing.JButton();
        jButtonAdminBlock = new javax.swing.JButton();

        jDialog1.setTitle("ATTENZIONE");
        jDialog1.setAlwaysOnTop(true);
        jDialog1.setBounds(new java.awt.Rectangle(0, 22, 250, 100));

        org.jdesktop.layout.GroupLayout jDialog1Layout = new org.jdesktop.layout.GroupLayout(jDialog1.getContentPane());
        jDialog1.getContentPane().setLayout(jDialog1Layout);
        jDialog1Layout.setHorizontalGroup(
            jDialog1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jDialog1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                .addContainerGap())
        );
        jDialog1Layout.setVerticalGroup(
            jDialog1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jDialog1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
                .addContainerGap())
        );

        setTitle("LIBRERIA");

        jButtonSearch.setText("CERCA");
        jButtonSearch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonSearchMouseClicked(evt);
            }
        });

        jButtonLogout.setText("LOGOUT");
        jButtonLogout.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonLogoutMouseClicked(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "USERNAME", "ID", "TITOLO", "TIPO", "SCADENZA", "SCADUTO", "RITORNATO"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setResizable(false);
        jTable1.getColumnModel().getColumn(3).setResizable(false);
        jTable1.getColumnModel().getColumn(4).setResizable(false);
        jTable1.getColumnModel().getColumn(5).setResizable(false);
        jTable1.getColumnModel().getColumn(6).setResizable(false);

        jButtonReturn.setText("RESTITUISCI");
        jButtonReturn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonReturnMouseClicked(evt);
            }
        });

        jButtonAdminAuthors.setText("GESTIONE AUTORI");
        jButtonAdminAuthors.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonAdminAuthorsMouseClicked(evt);
            }
        });

        jButtonAdminUsers.setText("GESTIONE UTENTI");
        jButtonAdminUsers.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonAdminUsersMouseClicked(evt);
            }
        });

        jButtonAdminLoans.setText("GESTIONE PRENOTAZIONI");
        jButtonAdminLoans.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonAdminLoansMouseClicked(evt);
            }
        });

        jButtonAdminProducts.setText("GESTIONE PRODOTTI");
        jButtonAdminProducts.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonAdminProductsMouseClicked(evt);
            }
        });

        jButtonAdminConfirm.setText("CONFERMA");
        jButtonAdminConfirm.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonAdminConfirmMouseClicked(evt);
            }
        });

        jButtonAdminBlock.setText("BLOCCA");
        jButtonAdminBlock.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonAdminBlockMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jLabelCurrent, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jButtonAdminProducts, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jButtonAdminAuthors, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jButtonAdminUsers, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jButtonSearch, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jButtonAdminLoans, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE))
                        .add(19, 19, 19)))
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(23, 23, 23)
                        .add(jButtonAdminConfirm)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jButtonAdminBlock)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 279, Short.MAX_VALUE)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jButtonLogout, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jButtonReturn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 130, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(layout.createSequentialGroup()
                        .add(18, 18, 18)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 624, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 180, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jLabelCurrent, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 34, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(88, 88, 88))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(jButtonSearch)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(jButtonAdminLoans)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(jButtonAdminUsers)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jButtonAdminAuthors)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButtonAdminProducts)))
                .add(22, 22, 22)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonReturn)
                    .add(jButtonAdminConfirm)
                    .add(jButtonAdminBlock))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButtonLogout)
                .add(60, 60, 60))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    /**
     * Cambia lo status dell'utente
     * @param i utente
     */
    private void lockUnlock(int i){
        library.getProducts().get(i).getRental().getOwner().setBlock();
        tableLoadAdmin();
    }

    /**
     * Resetta la tabella
     * @param size righe della tabella
     */
    private void tableReset(int size){
        DefaultTableModel tbl = (DefaultTableModel)jTable1.getModel();
        for(int i = 0;i < size;i++)
            tbl.removeRow(0);
    }
    /**
     * Carica la lista dei prestiti scaduti
     */
    private void tableLoadAdmin(){
        int size = jTable1.getRowCount();
        DefaultTableModel tbl = (DefaultTableModel)jTable1.getModel();
        for(int i = 0;i < size;i++)
            tbl.removeRow(0);
        for(Product a:library.getProducts()){
            if(a.isRented()){
                String uname = a.getRental().getOwner().getUsername();
                int i = a.getProductId();
                String title = a.getTitle();
                String ended = a.getRental().getEnd();
                String type = a.getType();
                boolean lock = !a.getRental().getOwner().canRent();
                boolean returns = a.getRental().returned();
                tbl.addRow(new Object[]{uname,i,title,type,ended,lock,returns});
            }
        }
    }

    /**
     * Carica la lista dei propri prestiti
     */
    private void tableLoad(){
        int size = jTable1.getRowCount();
        DefaultTableModel tbl = (DefaultTableModel)jTable1.getModel();
        tableReset(size);
        for(Product a:library.getProducts()){
            if(a.isRented() && a.getRental().getOwner().equals(user)){
                String uname = a.getRental().getOwner().getUsername();
                int i = a.getProductId();
                String title = a.getTitle();
                String end = a.getRental().getEnd();
                String type = a.getType();
                boolean lock = !a.getRental().isInTime();
                boolean returns = a.getRental().returned();
                tbl.addRow(new Object[]{uname,i,title,type,end,lock,returns});
            }
        }
    }

    /**
     * View della search
     * @param evt
     */
    private void jButtonSearchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonSearchMouseClicked
        //search
        new UserSearch(library,user,this).setVisible(true);
}//GEN-LAST:event_jButtonSearchMouseClicked

    /**
     * Restituzione prestito (solo utente normale)
     * @param evt
     */
    private void jButtonReturnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonReturnMouseClicked
        //ritorna prenotazione
        if(jTable1.getSelectedRow() > -1){
            Integer i = (Integer) jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 1);
            library.getProducts().get(i).getRental().setReturns();
            tableLoad();
        }
    }//GEN-LAST:event_jButtonReturnMouseClicked

    /**
     * View admin per amministrazione degli autori
     * @param evt
     */
    private void jButtonAdminAuthorsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAdminAuthorsMouseClicked
        /* AdminManageAuthors window */
        new AdminManageAuthors(library,this).setVisible(true);
}//GEN-LAST:event_jButtonAdminAuthorsMouseClicked

    /**
     * View admin per amministrazione degli utenti
     * @param evt
     */
    private void jButtonAdminUsersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAdminUsersMouseClicked
        /* AdminManageUsers window */
        new AdminManageUsers(library,this).setVisible(true);
}//GEN-LAST:event_jButtonAdminUsersMouseClicked

    /**
     * View comune per amministrazione prenotazioni
     * @param evt
     */
    private void jButtonAdminLoansMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAdminLoansMouseClicked
        /* AdminManageRentals window */
        new Bookings(library,user,this).setVisible(true);
}//GEN-LAST:event_jButtonAdminLoansMouseClicked

    /**
     * View admin per amministrazione dei prodotti
     * @param evt
     */
    private void jButtonAdminProductsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAdminProductsMouseClicked
        /* AdminManageProducts window */
        new AdminManageProducts(library,this).setVisible(true);
}//GEN-LAST:event_jButtonAdminProductsMouseClicked

    /**
     * Pulsante di logout
     * @param evt
     */
    private void jButtonLogoutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonLogoutMouseClicked
        this.setVisible(false);
        DefaultTableModel tbl = (DefaultTableModel)jTable1.getModel();
        tableReset(jTable1.getRowCount());
        login.setVisible(true);
    }//GEN-LAST:event_jButtonLogoutMouseClicked

    /**
     * Conferma la restituzione di una prenotazione
     * @param evt
     */
    private void jButtonAdminConfirmMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAdminConfirmMouseClicked
        if(jTable1.getSelectedRow() > -1){
            Integer i = (Integer) jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 1);
            library.getProducts().get(i).getRental().getOwner().setUnlock();
            library.getProducts().get(i).removeRental();
            tableLoadAdmin();
        }
    }//GEN-LAST:event_jButtonAdminConfirmMouseClicked

    /**
     * Blocca un utente
     * @param evt
     */
    private void jButtonAdminBlockMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAdminBlockMouseClicked
        if(jTable1.getSelectedRow() > -1){
            Integer i = (Integer) jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 1);
            lockUnlock(i);
            tableLoadAdmin();
        }
    }//GEN-LAST:event_jButtonAdminBlockMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAdminAuthors;
    private javax.swing.JButton jButtonAdminBlock;
    private javax.swing.JButton jButtonAdminConfirm;
    private javax.swing.JButton jButtonAdminLoans;
    private javax.swing.JButton jButtonAdminProducts;
    private javax.swing.JButton jButtonAdminUsers;
    private javax.swing.JButton jButtonLogout;
    private javax.swing.JButton jButtonReturn;
    private javax.swing.JButton jButtonSearch;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelCurrent;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

}
